package test.org.spring.boot.example.dds;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.spring.boot.example.dds.DynamicDataSource;
import org.spring.boot.example.dds.DynamicDataSourceAdvisorCreator;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@Import(DynamicDataSourceAdvisorCreator.class)
@ComponentScan("test.org.spring.boot.example.dds.service")
@PropertySource("test/org/spring/boot/example/dds/application.properties")
public class BootStartConfigution {

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.master")
	public DataSource master() {
		return new ComboPooledDataSource();
	}

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.slave-1")
	public DataSource slave1() {
		return new ComboPooledDataSource();
	}

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.logdb")
	public DataSource slave2() {
		return new ComboPooledDataSource();
	}

	@Bean
	@DependsOn({"master","slave1", "slave2"})  //DataSourceInitializerPostProcessor导致循环依赖问题
	public DataSource dataSource() {
		DynamicDataSource dynamicDataSource = new DynamicDataSource();
		Map<Object, Object> targetDataSources = new HashMap<>();
		targetDataSources.put("master", master());
		targetDataSources.put("slave-1", slave1());
		targetDataSources.put("logdb", slave2());
		dynamicDataSource.setTargetDataSources(targetDataSources);
		dynamicDataSource.setDefaultTargetDataSource(master());
		return dynamicDataSource;
	}

	@Bean
	public PlatformTransactionManager txManager() {
		return new DataSourceTransactionManager(dataSource());
	}

	@Bean
	public JdbcTemplate jdbcTemplate() {
		return new JdbcTemplate(dataSource());
	}

}
